import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor

from PyQt5.QtCore import *
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import *
# from PyQt5.uic import loadUi
from UI.Ui_MainWindow import MainWindow
import byzw

class Window:
    def __init__(self):
        # self.ui = loadUi('UI/MainWindow.ui')
        self.ui = MainWindow()
        self.initUi()

    def initUi(self):
        self.ui.btn_suggest.clicked.connect(self.getSuggestions)
        self.ui.btn_search.clicked.connect(self.searchBook)
        

        self.ui.table_results.setHorizontalHeaderLabels(['书名', '作者', '类型',  '更新时间', '操作'])
        self.ui.table_results.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def getSuggestions(self):
        surl = "https://www.81zw.com/"

        books = byzw.get_books(surl)
        self.ui.table_results.clear()
        self.ui.table_results.setHorizontalHeaderLabels(['书名', '作者', '类型',  '更新时间', '操作'])
        for i in range(len(books)):
            self.ui.table_results.insertRow(i)
            self.ui.table_results.setItem(i, 0, QTableWidgetItem(books[i]['title']))
            button = QPushButton(QIcon("UI/download.svg"), '下载')
            self.ui.table_results.setCellWidget(i, 4, button)
            # self.ui.table_results.setItem(i, 4, QTableWidgetItem(QIcon("UI/download.svg"), '下载'))

    def searchBook(self):
        kw = self.ui.lineEdit_search.text()
        books = byzw.search(kw)
        self.ui.table_results.clear()
        self.ui.table_results.setHorizontalHeaderLabels(['书名', '作者', '类型', '更新时间', '操作'])
        if not books:
            QMessageBox.information(self.ui, '提示', '未找到相关小说')
            return False
        
        for i in range(len(books)):
            self.ui.table_results.insertRow(i)
            self.ui.table_results.setItem(i, 0, QTableWidgetItem(books[i]['title']))
            self.ui.table_results.setItem(i, 1, QTableWidgetItem(books[i]['author']))
            self.ui.table_results.setItem(i, 2, QTableWidgetItem(books[i]['novel_type']))
            self.ui.table_results.setItem(i, 3, QTableWidgetItem(books[i]['update_time']))
        
            btn_download = QPushButton(QIcon("UI/download.svg"), '下载')
            btn_download.clicked.connect(lambda: self.download(books[self.ui.table_results.currentRow()]))

            self.ui.table_results.setCellWidget(i, 4, btn_download)


            # self.ui.table_results.setItem(i, 4, QTableWidgetItem(QIcon("UI/download.svg"), '下载'))
        # self.ui.table_results.itemClicked.connect(lambda: self.download(item=self.ui.table_results.currentItem(), book=books[self.ui.table_results.currentRow()]))
        

    def download(self, book):
        burl = book['burl']
        # print(burl)
        chapters = byzw.get_chapters(burl, book['title'])
        self.ui.textbrowser_download.append("目录解析完成，准备开始下载")

        dirname = os.getcwd() + '/' + book['title']
        if not os.path.exists(dirname):
            os.mkdir(dirname)

        p1 = int(len(chapters)/4)
        p2 = int(len(chapters)/2)
        p3 = int(len(chapters)*3/4)

        chapters1 = chapters[:p1]
        chapters2 = chapters[p1:p2]
        chapters3 = chapters[p2:p3]
        chapters4 = chapters[p3:]

        self.thread1 = DownloadThread(chapters1, self.ui.progressbar_1)
        self.thread2 = DownloadThread(chapters2, self.ui.progressbar_2)
        self.thread3 = DownloadThread(chapters3, self.ui.progressbar_3)
        self.thread4 = DownloadThread(chapters4, self.ui.progressbar_4)

        self.thread1.sig.connect(self.showDetails1)
        self.thread2.sig.connect(self.showDetails2)
        self.thread3.sig.connect(self.showDetails3)
        self.thread4.sig.connect(self.showDetails4)

        self.thread1.start()
        self.thread2.start()
        self.thread3.start()
        self.thread4.start()

        print("Done")

    def showDetails(self, chapter):
        self.ui.textbrowser_download.append(chapter+"\t下载完成")

    def showDetails1(self, info):
        info = eval(info)
        i = int(info[1])
        chapter = info[0]
        length = int(info[2])
        self.ui.textbrowser_download.append(chapter+"\t下载完成")
        self.ui.progressbar_1.setValue(int((i+1)/length*100))

    def showDetails2(self, info):
        info = eval(info)
        i = int(info[1])
        chapter = info[0]
        length = int(info[2])
        self.ui.textbrowser_download.append(chapter+"\t下载完成")
        self.ui.progressbar_2.setValue(int((i+1)/length*100))

    def showDetails3(self, info):
        info = eval(info)
        i = int(info[1])
        chapter = info[0]
        length = int(info[2])
        self.ui.textbrowser_download.append(chapter+"\t下载完成")
        self.ui.progressbar_3.setValue(int((i+1)/length*100))

    def showDetails4(self, info):
        info = eval(info)
        i = int(info[1])
        chapter = info[0]
        length = int(info[2])
        self.ui.textbrowser_download.append(chapter+"\t下载完成")
        self.ui.progressbar_4.setValue(int((i+1)/length*100))


class DownloadThread(QThread):
    sig = pyqtSignal(str)
    def __init__(self, chapters, progress):
        self.chapters = chapters
        self.progress = progress
        super(DownloadThread, self).__init__()

    def run(self):
        for i in range(len(self.chapters)):
            title = self.chapters[i]['title']
            link = self.chapters[i]['link']
            bookname = self.chapters[i]['bookname']
            content = byzw.get_content(link)
            filename = os.getcwd()+'/'+bookname+'/'+title+'.txt'
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(title+'\n'+content)
            self.sig.emit(str([title, str(i), str(len(self.chapters))]))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.ui.show()
    sys.exit(app.exec_())
